import fs from 'fs-extra';
import path from 'path';

import { initExecuteCommand, runHvigorAsync } from '../../common/common';
import { addOhPackageDps, buildAppAndHapsAndCheckFile, commonJson5Operation } from '../../plugins/common-fun';
import {
  AbilityType,
  APIType,
  APIVersion,
  CaseLevel,
  IsEnable,
  LanguageType,
  ModuleTemplateType,
  RuntimeOSType,
  SDKType,
  SignType
} from '../../plugins/project-builder/models/constants';
import { TestCaseBuilder } from '../../plugins/task-builder/task-case-builder';
import { ProjectBuildOption, TestCaseFun } from '../../plugins/task-builder/test-case';
import { TestTaskOption } from '../../plugins/task-builder/test-task-option';
import { OHOS_SIGNATURE_TEMPLATE } from '../../warable-api8/constants';

const projectBuilderOption: ProjectBuildOption = {
  template: {
    sdk: SDKType.Single,
    runtimeOS: RuntimeOSType.HarmonyOS,
    apiVersion: APIVersion.API11,
    apiType: APIType.STAGE,
    language: LanguageType.ArkTs,
    abilityType: AbilityType.Application,
    entryTemplateType: ModuleTemplateType.EmptyAbility,
  },
  modulesOption: {
    [ModuleTemplateType.SharedLibrary]: 1,
  }
};
const taskConfig: TestTaskOption = {
  caseLevel: CaseLevel.L1,
  sign: SignType.Sign,
  ohpmInstall: IsEnable.DisAble
};

const removeBuild = (rootPath: string, entryPath: string, libraryPath: string) => {
  // 清除产物 避免影响用例继续执行
  return Promise.all([
    fs.remove(path.resolve(rootPath, 'build')), fs.remove(path.resolve(entryPath, 'build')),
    fs.remove(path.resolve(libraryPath, 'build')),
  ]);
};

const testFun: TestCaseFun = async (project, taskConfig, record) => {
  const rootPath = project.projectRootPath();
  const entryPath = project.getModule('entry').moduleRootPath();
  const libraryPath = project.getModule('shareLibrary').moduleRootPath();
  const hspName = 'hsp_api12_jdk18'; // 分别存在于http://10.243.63.82:8088/repos/ohpm及https://7.190.6.197:8088/repos/ohpm
  const hspVersion = '1.0.2';
  await addOhPackageDps(entryPath, { [hspName]: hspVersion });
  await commonJson5Operation(path.resolve(rootPath, 'build-profile.json5'), async (json5): Promise<void> => {
    json5['app']['signingConfigs'] = [OHOS_SIGNATURE_TEMPLATE];
  });

  // 1.不配置enableSignTask直接构建hap、hsp
  await buildAppAndHapsAndCheckFile(project, taskConfig, record);
  const rootRemoteHspPath = path.resolve(rootPath, 'build', 'cache', 'default', 'remote_hsp',
    `${hspName}@${hspVersion}`, `${hspName}-signed.hsp`);
  expect(await fs.pathExists(rootRemoteHspPath)).toBe(true);
  await removeBuild(rootPath, entryPath, libraryPath);

  // 2.配置enableSignTask true后构建hap、hsp
  await commonJson5Operation(path.resolve(rootPath, 'hvigor', 'hvigor-config.json5'), async (json5): Promise<void> => {
    json5['properties'] = { 'enableSignTask': true };
  });
  await buildAppAndHapsAndCheckFile(project, taskConfig, record);
  expect(await fs.pathExists(rootRemoteHspPath)).toBe(true);
  await removeBuild(rootPath, entryPath, libraryPath);

  // 3.配置enableSignTask false后构建hap、hsp
  await commonJson5Operation(path.resolve(rootPath, 'hvigor', 'hvigor-config.json5'), async (json5): Promise<void> => {
    json5['properties'] = { 'enableSignTask': false };
  });

  // buildHaps方法中包含SignHap的校验 与enableSignTask:false冲突 此处自行实现
  const buildEntryCommands = initExecuteCommand({
    mode: 'module',
    product: 'default',
    tasks: 'assembleHap',
    module: 'entry@default',
  });
  const buildLibCommands = initExecuteCommand({
    mode: 'module',
    product: 'default',
    tasks: 'assembleHsp',
    module: 'shareLibrary@default',
  });
  const result1 = await runHvigorAsync(rootPath, buildEntryCommands);
  const result2 = await runHvigorAsync(rootPath, buildLibCommands);
  expect(result1.stdout).toContain('BUILD SUCCESSFUL');
  expect(result2.stdout).toContain('BUILD SUCCESSFUL');
  expect(await fs.pathExists(rootRemoteHspPath)).toBe(false); // remote_hsp要求不存在
  const entryOutputPath = path.resolve(entryPath, 'build', 'default', 'outputs', 'default');
  const libraryOutputPath = path.resolve(libraryPath, 'build', 'default', 'outputs', 'default');
  expect(await fs.pathExists(path.resolve(entryOutputPath, 'entry-default-unsigned.hap'))).toBe(true); // 要求只存在不签名包
  expect(await fs.pathExists(path.resolve(entryOutputPath, 'entry-default-signed.hap'))).toBe(false);
  expect(await fs.pathExists(path.resolve(libraryOutputPath, 'shareLibrary-default-unsigned.hsp'))).toBe(true);
  expect(await fs.pathExists(path.resolve(libraryOutputPath, 'shareLibrary-default-signed.hsp'))).toBe(false);
};

// 暂不执行本e2e，因依赖的个hsp规则规定必须是同版本的hvigor创的，导致hvigor版本更新后hsp需重新打包上传，本用例版本为 5.0.3.522
// TestCaseBuilder.builder()
//   .caseName('OPENLAB_AIDE_ZOS_DevEco_Studio_Build_SkipSignHap_Stage_26_04')
//   .description(`26、用户目录\\.hvigor\\hvigor-config.json5配置enableSignTask，win、mac模拟流水线CI场景构建Hap、Hsp包
//                 04、添加远程hsp依赖，用户目录\\.hvigor\\hvigor-config.json5配置enableSignTask，命令行构建hap包`)
//   .projectBuilderOption(projectBuilderOption)
//   .taskConfig(taskConfig)
//   .testFun(testFun)
//   .load();
